package me.kuye.jkuye.token;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.kuye.jkuye.core.Const;

public class TokenManager {

	private static ITokenCache tokenCache;

	public static void init(ITokenCache tokenCache) {
		if (tokenCache == null) {
			return;
		}
		TokenManager.tokenCache = tokenCache;
		long halfTimeout = Const.MIN_SECONDS_OF_TOKEN_TIME_OUT * 1000 / 2;
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				removeTimeTokenOut();
			}

		}, halfTimeout, halfTimeout);
	}

	private static void removeTimeTokenOut() {
		List<Token> tokenList = tokenCache.getAll();
		if (tokenList == null) {
			return;
		}

		List<Token> timeOutTokenList = new ArrayList<Token>();

		long currentTime = System.currentTimeMillis();
		for (Token token : tokenList) {
			if (token.getExpairTime() <= currentTime) {
				timeOutTokenList.add(token);
			}
		}
		for (Token token : timeOutTokenList) {
			tokenCache.remove(token);
		}
	}
}
